package com.bawei.module_home.ui.sign.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.Timer
import java.util.TimerTask
/**
 *author：yjk
 *description:
 *date：2025/6/12
*/
class TimeViewModel : ViewModel() {
    
    private val _currentTime = MutableLiveData<String>()
    val currentTime: LiveData<String> = _currentTime

    private val timer = Timer()
    private val formatter = SimpleDateFormat("HH:mm:ss", Locale.getDefault())
    //第一种
    init {
        // 每秒更新一次时间
        timer.schedule(object : TimerTask() {
            override fun run() {
                _currentTime.postValue(formatter.format(Date()))
            }
        }, 0, 1000) // 延迟0ms，间隔1000ms（1秒）
    }
    //第二种
    val timeFlow = flow {
        while (true) {
            emit(formatter.format(Date()))
            delay(1000)
        }
    }

    override fun onCleared() {
        super.onCleared()
        timer.cancel() // 避免内存泄漏
    }


}